package com.ruoyi.web.controller.finance;

import com.alibaba.fastjson2.JSONObject;
import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayUtil;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.finance.domain.Merchant;
import com.ruoyi.finance.domain.PayOrder;
import com.ruoyi.finance.mapper.MerchantMapper;
import com.ruoyi.finance.service.IPayOrderService;
import com.ruoyi.web.core.config.WeiPayConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.ruoyi.common.utils.uuid.IdUtils.get16UUID;

/**
 * 支付订单Controller
 *
 * @author zt
 * @date 2023-11-15
 */
@RestController
@RequestMapping("/order")
public class PayOrderController extends BaseController {

    @Autowired
    private IPayOrderService payOrderService;

    @Autowired
    private MerchantMapper merchantMapper;

    @Value("${notifyUrl.weichatPay}")
    private String notifyIpPort;

    /**
     * 新增支付订单
     */
    @Log(title = "申请支付订单", businessType = BusinessType.INSERT)
    @PostMapping("/applyPayOrder")
    public AjaxResult add(@RequestBody PayOrder payOrder) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        payOrder.setPayType("1");
        payOrder.setOutTradeNo(get16UUID("JUFA"));
        HashMap<String, String> data = new HashMap<>();
        data.put("body", payOrder.getBody()); //商品描述
        data.put("out_trade_no", payOrder.getOutTradeNo()); //使用当前用户订单的编号作为当前支付交易的交易号
        data.put("fee_type", "CNY"); //支付币种
        BigDecimal totalFee = payOrder.getTotalFee();
        data.put("total_fee", String.valueOf(totalFee.multiply(new BigDecimal(100)).intValue())); //支付额
        data.put("trade_type", "NATIVE"); //交易类型
        data.put("attach", loginUser.getUserId().toString()); //交易类型
        data.put("notify_url", notifyIpPort + "/order/payNotify"); //设置支付完成时的回调方法法接口
        WXPay wxPay = new WXPay(new WeiPayConfig());
        Map<String, String> resp; //发送请求
        try {
            resp = wxPay.unifiedOrder(data);
        } catch (Exception e) {
            e.printStackTrace();
            return error("支付异常");
        }
        payOrder.setTradeState("NOTPAY");
        payOrderService.insertPayOrder(payOrder);
        JSONObject reJsson = new JSONObject();
        reJsson.put("payUrl", resp.get("code_url"));
        reJsson.put("outTradeNo", payOrder.getOutTradeNo());
        reJsson.put("totalTee", payOrder.getTotalFee());
        return success(reJsson);
    }

    /**
     * 修改支付订单(回调)
     */
    @Log(title = "支付订单", businessType = BusinessType.UPDATE)
    @Anonymous
    @PostMapping("/payNotify")
    public String edit(HttpServletRequest request) throws Exception {
        // 1.接收微信支付平台传递的数据（使用request的输入流接收）
        ServletInputStream is = request.getInputStream();
        byte[] bs = new byte[1024];
        int len;
        StringBuilder builder = new StringBuilder();
        while ((len = is.read(bs)) != -1) {
            builder.append(new String(bs, 0, len));
        }
        String s = builder.toString();
        //使用帮助类将xml接口的字符串装换成map
        Map<String, String> map = WXPayUtil.xmlToMap(s);
        if (map != null && "success".equalsIgnoreCase(map.get("result_code"))) { //支付成功
            //2.修改订单状态为 已支付 充值
            int success = payOrderService.updatePayOrderStatus(map);
            //3.响应微信支付平台
            if (success == 2) {
                HashMap<String, String> resp = new HashMap<>();
                resp.put("return_code", "success");
                resp.put("return_msg", "OK");
                resp.put("appid", map.get("appid"));
                resp.put("result_code", "success");
                return WXPayUtil.mapToXml(resp);
            }
        }
        return null;
    }

    /**
     * 查询支付订单列表
     */
    @GetMapping("/list")
    public TableDataInfo list(PayOrder payOrder) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        List<SysRole> roles = loginUser.getUser().getRoles();
        for (SysRole sysRole : roles) {
            if (!("admin".equals(sysRole.getRoleKey()) || "yewuadmin".equals(sysRole.getRoleKey()))) {    // 非管理员
                String merchantCode = merchantMapper.selectMerchantByUserOne(new Merchant(loginUser.getUserId())).getMerchantCode();
                payOrder.setAccount(merchantCode);
            }
        }
        startPage();
        List<PayOrder> list = payOrderService.selectPayOrderList(payOrder);
        return getDataTable(list);
    }

    /**
     * 轮询支付订单
     */
    @GetMapping(value = "/lunxun/{outTradeNo}")
    public AjaxResult getInfo(@PathVariable("outTradeNo") String outTradeNo) {
        PayOrder payOrder = payOrderService.selectPayOrderByOutTradeNo(outTradeNo);
        if (payOrder != null) {
            return success("ok");
        } else {
            return success("no");
        }
    }

    /**
     * 导出支付订单列表
     */
    @Log(title = "支付订单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, PayOrder payOrder) {
        List<PayOrder> list = payOrderService.selectPayOrderList(payOrder);
        ExcelUtil<PayOrder> util = new ExcelUtil<PayOrder>(PayOrder.class);
        util.exportExcel(response, list, "支付订单数据");
    }

}
